<?php
App::uses('AppController','Controller');
class VehiculosController extends AppController {
	
	var $uses = array('Vehiculo','Cliente','CatalogoDetalle'); 
	var $components = array('Constantes');

	function beforeFilter(){
		if(!$this->Session->check('usuarioSesionSOT')){
			$this->redirect(array('controller'=>'Seguridad','action'=>'login'));
		}else{
			$this->set('usuarioSesionSOT',$this->Session->read('usuarioSesionSOT'));
		}
	}
	
	public function index(){
        $this->redirect(array('controller'=>'Vehiculos','action'=>'consultar_vehiculos'));
    }
    
    public function consultar_vehiculos(){
    	$this->layout = 'plantillaPrincipal';
    	$this->set('title_for_layout', '::Veh&iacute;culos::');
 
    	//Cargar los combos
    	$this->fn_cargarCombos();
    	
    	//Buscar los clientes
    	$idCliente = (isset($this->request->data['idCliente']))?$this->request->data['idCliente']:"";
    	$numeroPlaca = (isset($this->request->data['numeroPlaca']))?$this->request->data['numeroPlaca']:"";
    	$idMarcaVehiculo = (isset($this->request->data['idMarcaVehiculo']))?$this->request->data['idMarcaVehiculo']:"";
    	$modelo = (isset($this->request->data['modelo']))?$this->request->data['modelo']:"";
    	$idTipoCombustible = (isset($this->request->data['idTipoCombustible']))?$this->request->data['idTipoCombustible']:"";

    	$condiciones = array();
    	$condiciones["idCliente"] = $idCliente;
    	$condiciones["numeroPlaca"] = $numeroPlaca;
    	$condiciones["idMarcaVehiculo"] = $idMarcaVehiculo;
    	$condiciones["modelo"] = $modelo;
    	$condiciones["idTipoCombustible"] = $idTipoCombustible;
    	
    	$this->set("condiciones",$condiciones);
    	
    	$vehiculosArrayJSON = $this->fn_buscar_vehiculos_json($condiciones);
    	$this->set('vehiculosArrayJSON',$vehiculosArrayJSON);
    	
    	//Tomar el mensaje de accion si es que existiese
    	if($this->Session->check('msjRegistroVehiculo')){
     		$this->set('msjRegistroVehiculo',$this->Session->read("msjRegistroVehiculo"));
			$this->Session->delete('msjRegistroVehiculo');
    	}
    }
    
    public function nuevo_vehiculo(){
    	$this->layout = 'plantillaPrincipal';
    	$this->set('title_for_layout', '::Veh&iacute;culos::');
    	$this->fn_cargarCombos();
    }
    
    public function guardar_vehiculo(){
    	
    	$this->layout = 'plantillaPrincipal';
    	
    	//Tomar los datos
    	if(isset($this->request->data)){
    		
    		$usuarioSesionSOT = $this->Session->read('usuarioSesionSOT');
  			$usuarioRegistro = $usuarioSesionSOT["Usuario"]["idUsuario"];
    		$fechaRegistro = date_create()->format('Y-m-d H:i:s');
    		
    		$dataSource = $this->Vehiculo->getDataSource();
    		
    		$dataSource->begin();

    		$data = $this->request->data["Vehiculo"];
    		
    		//Verificar el id , si esta vacio se solicita a la BD
    		$idVehiculo = "";
    		if(isset($data["idVehiculo"])){
    			if($data["idVehiculo"] != ""){
    				$idVehiculo = $data["idVehiculo"];
    			}
    		}
    		
    		$correlativo = "";
    		if($idVehiculo == ""){
    			$prefijo = "VE";
    			
    			$longitudPrefijo = strlen($prefijo);
    			$longitudCorrelativo = 8;
    			$rs = $this->Vehiculo->query("select (ifnull(convert((select substring(max(idVehiculo),".($longitudPrefijo+1).",".$longitudCorrelativo.") from Vehiculos),decimal),0)+1) as 'correlativo'");
    			$correlativo = $rs[0][0]["correlativo"];

    			while(strlen($correlativo)<($longitudCorrelativo)){
    				$correlativo = "0".$correlativo;
    			}
    			
    			$correlativo = $prefijo.$correlativo;
    			
    			$objVehiculo["Vehiculo"]["idUsuarioCreacion"] = $usuarioRegistro;
    			$objVehiculo["Vehiculo"]["fechaCreacion"] = $fechaRegistro;
    		}else{
    			$correlativo = $data["idVehiculo"];
    			$objVehiculo = $this->Vehiculo->find('first',array('conditions' => array('Vehiculo.idVehiculo' =>$correlativo)));
    			$objVehiculo["Vehiculo"]["idUsuarioModifica"] = $usuarioRegistro;
    			$objVehiculo["Vehiculo"]["fechaModifica"] = $fechaRegistro;
    		}
    		
    		//Preparar los datos
    		$objVehiculo["Vehiculo"]["idVehiculo"] = $correlativo;
    		$objVehiculo["Vehiculo"]["numeroPlaca"] = $data["numeroPlaca"];
  			$objVehiculo["Vehiculo"]["anio"] = $data["anio"];
  			$objVehiculo["Vehiculo"]["color"] = $data["color"];
  			
  			if($data["idCliente"] == ""){
  				$objVehiculo["Vehiculo"]["idCliente"] = null;
  			}else{
  				$objVehiculo["Vehiculo"]["idCliente"] = $data["idCliente"];
  			}
  			
  			$objVehiculo["Vehiculo"]["idMarcaCatalogo"] = $this->Constantes->MARCAS_VEHICULOS;
  			$objVehiculo["Vehiculo"]["idMarcaItem"] = $data["idMarcaItem"];
  			$objVehiculo["Vehiculo"]["modelo"] = $data["modelo"];
  			$objVehiculo["Vehiculo"]["idCombustibleCatalogo"] = $this->Constantes->TIPOS_COMBUSTIBLES;
  			$objVehiculo["Vehiculo"]["idCombustibleItem"] = $data["idCombustibleItem"];
  			
  			if ($this->Vehiculo->save($objVehiculo)) {
  				if($idVehiculo == ""){
  					$this->Session->write('msjRegistroVehiculo',"Se registr&oacute; al veh&iacute;culo exitosamente");
  				}else{
  					$this->Session->write('msjRegistroVehiculo',"Se actualiz&oacute; al veh&iacute;culo exitosamente");
  				}
  				
  				$dataSource->commit();
  				$this->redirect(array('controller'=>'Vehiculos','action'=>'editar_vehiculo',"?" => array("idVehiculo" => $correlativo)));
  			}else{
  				if($idVehiculo == ""){
  					$this->Session->write('msjRegistroVehiculo',"No se pudo registrar al veh&iacute;culo");
  				}else{
  					$this->Session->write('msjRegistroVehiculo',"No se pudo actualizar al veh&iacute;culo");
  				}
  				$dataSource->rollback();
  				$this->redirect(array('controller'=>'Vehiculos','action'=>'consultar_vehiculos'));
  			}
    	}else{
    		$this->redirect(array('controller'=>'Vehiculos','action'=>'consultar_vehiculos'));
    	}
    }
    
	public function editar_vehiculo(){
    	$this->layout = 'plantillaPrincipal';
    	$this->set('title_for_layout', '::Veh&iacute;culos::');
    	if(isset($this->request->query['idVehiculo'])){
    		$idVehiculo = $this->request->query['idVehiculo'];
    	
    		$objVehiculo = $this->Vehiculo->find('first',array('conditions' => array('Vehiculo.idVehiculo' => $idVehiculo)));
    
    		if(count($objVehiculo)>0){
    			$this->fn_cargarCombos();
    			$this->set("objVehiculo",$objVehiculo);
    			
    		    //Tomar el mensaje de accion si es que existiese
		    	if($this->Session->check('msjRegistroVehiculo')){
		     		$this->set('msjRegistroVehiculo',$this->Session->read("msjRegistroVehiculo"));
					$this->Session->delete('msjRegistroVehiculo');
		    	}
    	
    			$this->render('nuevo_vehiculo');
    		}else{
    			$this->redirect(array('controller'=>'Vehiculos','action'=>'consultar_vehiculos'));
    		}
    	}else{
    		$this->redirect(array('controller'=>'Vehiculos','action'=>'consultar_vehiculos'));
    	}
    }
    
    public function listar_vehiculos_x_cliente_json(){
    	$this->layout = 'ajax';
    	
    	$vehiculosArrayJSON = array();
    	if(isset($this->request->query['idCliente'])){
    		$idCliente = $this->request->query['idCliente'];
    		$lstVehiculos = $this->Vehiculo->find('all',array('conditions' => array('Vehiculo.idCliente' => $idCliente),'order'=>'Vehiculo.numeroPlaca asc'));
    		
    		$i = 0;
    		$dim = count($lstVehiculos);
    		
    		while($i<$dim){
    			$objVehiculo = $lstVehiculos[$i];
    			
    			$objVehiculoJSON = array();
    			$objVehiculoJSON["idVehiculo"] = $objVehiculo["Vehiculo"]["idVehiculo"];
    			$objVehiculoJSON["numeroPlaca"] = $objVehiculo["Vehiculo"]["numeroPlaca"];
    			$objVehiculoJSON["color"] = $objVehiculo["Vehiculo"]["color"];
    			$objVehiculoJSON["anio"] = $objVehiculo["Vehiculo"]["anio"];
    			$objVehiculoJSON["marcaVehiculo"] = $objVehiculo["MarcaVehiculo"]["descripcion"];
    			$objVehiculoJSON["tipoCombustible"] = $objVehiculo["Combustible"]["descripcion"];
    			
    			$vehiculosArrayJSON[$i] = $objVehiculoJSON;
    			$i = $i + 1;	
    		}
    	}
    	
    	$this->set('vehiculosArrayJSON',$vehiculosArrayJSON);
    }
    
	private function fn_buscar_vehiculos_json($condiciones){
    	$arrayJSON = array();
    	
    	$idCliente = $condiciones["idCliente"];
    	$numeroPlaca = $condiciones["numeroPlaca"];
    	$modelo = $condiciones["modelo"];
		$idMarcaVehiculo = $condiciones["idMarcaVehiculo"];
		$idTipoCombustible = $condiciones["idTipoCombustible"];
		
    	$sql = "select v.idVehiculo,
    				   v.numeroPlaca,
    				   v.modelo,
    				   v.anio,
    				   marca.descripcion,
    				   v.color,
    				   combustible.descripcion,
    				   c.nombreEntidad from 
    				   Vehiculos v 
    				   left join Clientes c on v.idCliente = c.idCliente 
    				   left join CatalogoDetalle marca on (v.idMarcaCatalogo = marca.idCatalogo and v.idMarcaItem = marca.idItem) 
    				   left join CatalogoDetalle combustible on (v.idCombustibleCatalogo = combustible.idCatalogo and v.idCombustibleItem = combustible.idItem) where ";
    				   
    	if($idCliente != ""){
    		$sql = $sql."v.idCliente like '".$idCliente."%' and ";
		}else{
			$sql = $sql."(v.idCliente like '".$idCliente."%' or v.idCliente is null) and ";
		}
		
		if($modelo != ""){
			$sql = $sql."v.modelo like '".$modelo."%' and ";
		}else{
			$sql = $sql."(v.modelo like '".$modelo."%' or v.modelo is null) and ";
		}

		$sql = $sql." v.numeroPlaca like '".$numeroPlaca."%' and v.idMarcaCatalogo = ".$this->Constantes->MARCAS_VEHICULOS." and v.idMarcaItem like '".$idMarcaVehiculo."%' and
    				  v.idCombustibleCatalogo = ".$this->Constantes->TIPOS_COMBUSTIBLES." and v.idCombustibleItem like '".$idTipoCombustible."%' order by v.numeroPlaca asc";
    	
    	$vehiculos = $this->Vehiculo->query($sql);
    	$i = 0;
    	$dim = count($vehiculos);
    	
    	$vehiculosArrayJSON = array();
    	while($i<$dim){
    		
    		$objVehiculo = $vehiculos[$i];
    		$objJson = array();
    		$objJson["id"] = $objVehiculo["v"]["idVehiculo"];
    		$objJson["numeroPlaca"] = $objVehiculo["v"]["numeroPlaca"];
    		$objJson["anio"] = $objVehiculo["v"]["anio"];
    		$objJson["marcaVehiculo"] = $objVehiculo["marca"]["descripcion"];
    		$objJson["modelo"] = $objVehiculo["v"]["modelo"];
    		$objJson["color"] = $objVehiculo["v"]["color"];
    		$objJson["combustible"] = $objVehiculo["combustible"]["descripcion"];
    		
    		$objCliente = $objVehiculo["c"];
    		$objJson["nombreCliente"] = $objCliente["nombreEntidad"];

    		$vehiculosArrayJSON[$i] = $objJson;
    		$i = $i + 1;
    	}
    	return $vehiculosArrayJSON;
    }
    
    private function fn_cargarCombos(){

    	//Traer el listado de clientes
    	$clientes = $this->Cliente->find('all',array('order'=>'Cliente.nombreEntidad asc'));
    	$this->set('clientes',$clientes);
    	
    	//Traer el listado de marcas de vehiculos
    	$contidions = array();
    	$conditions["CatalogoDetalle.idCatalogo"] = $this->Constantes->MARCAS_VEHICULOS;
    	$marcasVehiculos = $this->CatalogoDetalle->find('all',array('conditions'=>$conditions,'order'=>'CatalogoDetalle.descripcion asc'));
    	$this->set('marcasVehiculos',$marcasVehiculos);
    	
    	//Traer el listado de tipos de combustibles
    	$contidions = array();
    	$conditions["CatalogoDetalle.idCatalogo"] = $this->Constantes->TIPOS_COMBUSTIBLES;
    	$tiposCombustibles = $this->CatalogoDetalle->find('all',array('conditions'=>$conditions,'order'=>'CatalogoDetalle.numOrden asc'));
    	$this->set('tiposCombustibles',$tiposCombustibles);
    }
}
?>